<template>
  <div class="choose-object">
    <a-select
      v-model="myManager"
      showSearch
      :mode="single ? 'default' : 'multiple'"
      class="select-manager"
      option-label-prop="label"
      :disabled="optFlag == 3"
      @search="selectSearch"
      @focus="searchData = []"
      @select="selectEvent"
      @change="selectChange"
      :getPopupContainer="(triggerNode) => triggerNode.parentNode"
    >
      <a-select-option
        v-for="item in searchData"
        :key="item.userId"
        :value="item.type + '/' + item.userId + '/' + item.uname"
        :label="item.uname"
        >{{ item.uname }}</a-select-option
      >
    </a-select>
    <a-button
      :disabled="optFlag == 3"
      style="width: 64px;height:40px;"
      type="primary"
      @click="chooseEvent"
      >选择</a-button
    >
    <a-modal
      :title="modalTitle"
      :visible="myVisible"
      centered
      width="850px"
      :maskClosable="false"
      @cancel="myVisible = false"
    >
      <div class="quik-search">
        <span>快速查询：</span>
        <a-input
          style="width: 320px"
          placeholder="请输入姓名,多条件以空格分开（如：张 王）"
          v-model="keywords"
          @pressEnter="searchChoose()"
        />
        <a-button type="primary" @click="searchChoose()">查询</a-button>
      </div>
      <div class="container">
        <div class="card-container">
          <a-tabs size="small" type="card" v-if="myVisible" v-model="tabValue" @change="tabChange">
            <a-tab-pane
              :key="tabitem.key"
              :tab="tabitem.name"
              v-for="tabitem in selectConfig"
            >
              <div class="tab-content">
                <a-checkbox-group @change="leftCheckBoxChange">
                  <a-collapse
                    v-model="collapseValue"
                    expand-icon-position="right"
                  >
                    <a-collapse-panel
                      v-for="(item, i) in leftSelectData"
                      :key="`${i}`"
                    >
                      <template slot="header">
                        <div class="header-content">
                          <i
                            class="suncnui suncnui-icon-jiegou menu_head_select_ico"
                          ></i>
                          {{ item.name }}
                        </div>
                      </template>
                      <div
                        class="secondary-li"
                        v-for="v in item.childList"
                        :key="v.id"
                      >
                        <a-row type="flex" justify="space-between">
                          <a-col :span="16">
                            <div class="select-item">
                              <a-checkbox :value="v.id" v-if="tabitem.isShowCheck"
                                >{{ v.name }}({{ v.count }})</a-checkbox
                              >
                              <span class="second-text" v-else
                                >{{ v.name }}({{ v.count }})</span
                              >
                            </div>
                          </a-col>
                          <a-col>
                            <span class="next-level" @click="clickNextLevel(v)"
                              >下级</span
                            >
                          </a-col>
                        </a-row>
                      </div>
                    </a-collapse-panel>
                  </a-collapse>
                </a-checkbox-group>
              </div>
            </a-tab-pane>
          </a-tabs>
        </div>
        <div class="right-choice">
          <div class="right-title right-title-box">
      
            <div>已选中（{{ this.checkedArr.length }}）</div>
            <div class="breadcrumb">
              <span class="all-btn" @click="breadcrumbAllBtn">全部</span>
              <div v-if="breadcrumbText !== ''">
                <span><i class="suncnui suncnui-icon-zuo1"></i></span>
                <span>{{ breadcrumbText }}</span>
              </div>
            </div>
          </div>
          <div class="check-list">
            <a-table
              :row-selection="{
                selectedRowKeys: selectedRowKeys,
                onChange: onSelectChange
              }"
              :columns="columns"
              :data-source="tabelData"
              v-if="!single"
              rowKey="userId"
              :pagination="false"
              :scroll="{ y: '257px' }"
            />
            <a-table
              :row-selection="{
                selectedRowKeys: selectedRowKeys,
                onChange: onSelectChange,
                type: 'radio'
              }"
              :columns="columns"
              :data-source="tabelData"
              rowKey="userId"
              :pagination="false"
              v-else
            />
          </div>
          <span class="area-split"></span>
          <div class="checked-tags">
            <!-- 已选择对象 -->
            <a-tag
              v-for="item in checkedArr"
              :key="item.userId"
              color="blue"
              closable
              @close="tagClose(item.userId)"
              >{{ item.uname }}</a-tag
            >
          </div>
        </div>
      </div>
      <template slot="footer">
        <div class="footer-btns">
          <a-button type="primary" @click="handleOk">确定</a-button>
          <a-button @click="reset">清空</a-button>
          <a-button @cancel="myVisible = false">取消</a-button>
        </div>
      </template>
    </a-modal>
  </div>
</template>

<script>
import { selectData, selectUser } from '@/api/component'
export default {
  components: {},
  data() {
    return {
      myVisible: false,
      searchData: [],//下拉框搜索数据
      allUserData:[],//缓存弹框里面所有数据
      myManager: [],
      selectInputArr:[],//缓存弹框选中的值
      tabValue: 'u', //tab切换的值
      breadcrumbText: '', //二级面包屑值
      selectedRowKeys: [], //表格选择数据
      columns: [
        {
          title: '姓名',
          dataIndex: 'uname'
        },
        {
          title: '界别',
          dataIndex: 'faction'
        },
        {
          title: '党派',
          dataIndex: 'sector'
        },
        {
          title: '职务',
          dataIndex: 'duty'
        }
      ],
      tabelData: [
        {
          uname: '李佳10066',
          fmanagerDuty: null,
          faction: '民盟',
          duty: '市长',
          userId: '10066',
          sector: '民革',
          fmanagerName: null
        },
        {
          uname: '李佳10770',
          fmanagerDuty: null,
          faction: '民盟',
          duty: '市长',
          userId: '10770',
          sector: '民革',
          fmanagerName: null
        },
        {
          uname: '李佳10934',
          fmanagerDuty: null,
          faction: '民盟',
          duty: '市长',
          userId: '10934',
          sector: '民革',
          fmanagerName: null
        },
        {
          uname: '李佳10389',
          fmanagerDuty: null,
          faction: '民盟',
          duty: '市长',
          userId: '10389',
          sector: '民革',
          fmanagerName: null
        },
        {
          uname: '李佳10223',
          fmanagerDuty: null,
          faction: '民盟',
          duty: '市长',
          userId: '10223',
          sector: '民革',
          fmanagerName: null
        },
        {
          uname: '李佳10702',
          fmanagerDuty: null,
          faction: '民盟',
          duty: '市长',
          userId: '10702',
          sector: '民革',
          fmanagerName: null
        },
        {
          uname: '李佳10161',
          fmanagerDuty: null,
          faction: '民盟',
          duty: '市长',
          userId: '10161',
          sector: '民革',
          fmanagerName: null
        },
        {
          uname: '李佳10840',
          fmanagerDuty: null,
          faction: '民盟',
          duty: '市长',
          userId: '10840',
          sector: '民革',
          fmanagerName: null
        },
        {
          uname: '李佳10630',
          fmanagerDuty: null,
          faction: '民盟',
          duty: '市长',
          userId: '10630',
          sector: '民革',
          fmanagerName: null
        },
        {
          uname: '李佳10977',
          fmanagerDuty: null,
          faction: '民盟',
          duty: '市长',
          userId: '10977',
          sector: '民革',
          fmanagerName: null
        },
        {
          uname: '李佳10018',
          fmanagerDuty: null,
          faction: '民盟',
          duty: '市长',
          userId: '10018',
          sector: '民革',
          fmanagerName: null
        },
        {
          uname: '李佳10057',
          fmanagerDuty: null,
          faction: '民盟',
          duty: '市长',
          userId: '10057',
          sector: '民革',
          fmanagerName: null
        },
        {
          uname: '李佳10570',
          fmanagerDuty: null,
          faction: '民盟',
          duty: '市长',
          userId: '10570',
          sector: '民革',
          fmanagerName: null
        }
      ],
      collapseValue: '0', //折叠面板
      leftSelectData: [
        // {
        //   code: null,
        //   name: '党派',
        //   count: null,
        //   childList: [
        //     {
        //       code: '01',
        //       name: '中共',
        //       count: 0,
        //       childList: null,
        //       type: '党派'
        //     },
        //     {
        //       code: '02',
        //       name: '民革',
        //       count: 0,
        //       childList: null,
        //       type: '党派'
        //     },
        //     {
        //       code: '03',
        //       name: '民盟',
        //       count: 1001,
        //       childList: null,
        //       type: '党派'
        //     },
        //     {
        //       code: '04',
        //       name: '民建',
        //       count: 1,
        //       childList: null,
        //       type: '党派'
        //     },
        //     {
        //       code: '05',
        //       name: '民进',
        //       count: 1,
        //       childList: null,
        //       type: '党派'
        //     },
        //     {
        //       code: '06',
        //       name: '农工党',
        //       count: 1,
        //       childList: null,
        //       type: '党派'
        //     }
        //   ],
        //   type: '-1'
        // },
        // {
        //   code: null,
        //   name: '界别',
        //   count: null,
        //   childList: [
        //     {
        //       code: '22',
        //       name: '农业',
        //       count: 0,
        //       childList: null,
        //       type: '界别'
        //     },
        //     {
        //       code: '01',
        //       name: '中共',
        //       count: 0,
        //       childList: null,
        //       type: '界别'
        //     },
        //     {
        //       code: '23',
        //       name: '教育',
        //       count: 0,
        //       childList: null,
        //       type: '界别'
        //     },
        //     {
        //       code: '02',
        //       name: '民革',
        //       count: 1003,
        //       childList: null,
        //       type: '界别'
        //     },
        //     {
        //       code: '24',
        //       name: '体育',
        //       count: 0,
        //       childList: null,
        //       type: '界别'
        //     }
        //   ],
        //   type: '-1'
        // }
      ],
      keywords: '',
      loading: false,
      searchUser: [
        {
          id: 1,
          name: '定中四'
        },
        {
          id: 2,
          name: '定中爱'
        },
        {
          id: 3,
          name: '定试试'
        }
      ],
      checkedUser: [],
      checkedArr: [], //当前已选对象列表
      indeterminate: false,
      checkAll: false
    }
  },
  props: {
    form: {
      type: Object,
      default: () => {}
    },
    manager: {
      //默认选择 回显
      type: Array,
      default: () => []
    },
    single: {
      //是否多选
      type: Boolean,
      default: true
    },
    modalTitle: {
      //弹出层名字
      type: String,
      default: '选择机构用户'
    },
    chooseType: {
      //选择类型
      type: String,
      default: 'u'
    },
    sessionId: {
      //界次传入
      type: String,
      default: ''
    },
    filterPerson: {
      //传入的需要过滤人员的数组
      type: Array,
      default: () => [
        {
          userId:'10840'
        },
        {
          userId:'10630'
        }
      ]
    },
    selectConfig: {
      //配置tab
      type: Array,
      default: () => [
        {
          name: '委员',
          key: 'u',
          isShowCheck: true //是否显示复选框
        },
        {
          name: '上报单位',
          key: 'c',
          isShowCheck: false
        },
        {
          name: '承办单位',
          key: 't',
          isShowCheck: false
        }
      ]
    },
    optFlag: {
      type: Number,
      default: 1 // 1新增 2编辑 3查询
    }
  },
  mounted() {
    this.manager.forEach((item) => {})
    this.getSelectData()
    this.getAllSearchData()
  },
  methods: {
    filterAllData(filterId,data){
      filterId.forEach((v)=>{
      const index = data.findIndex(
        (item) => item === v.userId || item.userId === v.userId
        )
        data.splice(index,1)
      })
      return data
    },
    tabChange(){//tab切换
      this.getSelectData()
      this.breadcrumbAllBtn()
    },
    selectSearch(val) {
      this.searchData = []
      if (!val) {
        return false
      }
      selectUser({type: this.chooseType })
        .then((res) => {
          let data = res.data.totalData
            data.forEach((item) => {
              item.type = this.chooseType
              this.searchData.push(item)
            })
        })
        .catch((err) => {
          this.$message.destroy()
          this.$message.error(err)
        })
    },
    //选择
    chooseEvent() {
      this.myVisible = !this.myVisible
      this.checkedArr = []
      this.selectedRowKeys = []
      this.myManager.forEach((item) => {
        let datas = item.split('/')
        this.checkedArr.push({ type: datas[0], userId: datas[1], uname: datas[2] })
        this.selectedRowKeys.push(datas[1])
      })
    },
    selectChange(value) {
      var itemArr = []
      var valueArr = []
      var valueIdArr = []
      if (value instanceof Array) {
        //多选模式下  选中的值为数组
        value.forEach((item) => {
          var obj = {}
          itemArr = item.split('/')
          obj.type = itemArr[0]
          obj.userId = itemArr[1]
          obj.uname = itemArr[2]
          valueArr.push(obj)
          valueIdArr.push(obj.userId)
        })
      } else {
        //单选模式下  选中的值为字符串
          var obj = {}
          itemArr = value.split('/')
          obj.type = itemArr[0]
          obj.userId = itemArr[1]
          obj.uname = itemArr[2]
          valueArr.push(obj)
          valueIdArr.push(obj.userId)
      }
      this.$emit('selectFunc', valueArr)
    },
    //下拉选中
    selectEvent(val) {
      if (this.single) {
        this.myManager = [val]
      }
    },
    //获取左侧选择的数据
    getSelectData() {
      let params = {
        kind:this.tabValue
      }
      selectData(params).then((res)=> {
        this.leftSelectData = res.data.data
        this.dataDeal(this.leftSelectData)
      }).catch((err) => {
          this.$message.destroy()
          this.$message.error(err)
      }).finally(() => {
          
      })
    },
   
    getAllSearchData(){
      selectUser({type: this.chooseType })
        .then((res) => {
          var searchArr = []
          if(this.tabValue == 'u'){
            var data = res.data.allData
          } else {
            var data = res.data.allData2
          }
          this.tabelData  = data
          res.data.totalData.forEach((item) => {
              item.type = this.chooseType
              searchArr.push(item)
          })
          this.searchData = searchArr
          if(this.filterPerson.length>0){
            this.allUserData = this.filterAllData(this.filterPerson,res.data.totalData)
          }else{
            this.allUserData = res.data.totalData
          } 
          console.log(this.allUserData)
        })
        .catch((err) => {
          this.$message.destroy()
          this.$message.error(err)
        })
    },
    dataDeal(data) {
      const list = data.map((item) => {
        item.childList = item.childList.map((child) => {
          let temp = {
            code: child.code,
            name: child.name,
            count: child.count,
            childList: child.child,
            type: child.type,
            id: child.code + '_' + child.type
          }
          return temp
        })
        return item
      })
      this.leftSelectData = list
    },
    leftCheckBoxChange(value) {
      //左侧复选框事件
      console.log(value)
      var param = {
        kind:this.tabValue
        // userId:item.userId,
        // uname:item.uname
      }
      selectUser(param)
        .then((res) => {
          if(this.tabValue == 'u'){
            var data = res.data.data1
          } else {
            var data = res.data.data2
          }
          this.checkedArr = data
          const selectedRowKeysId = []
          this.checkedArr.forEach((item)=>{
            selectedRowKeysId.push(item.userId)
          })
          this.selectedRowKeys = selectedRowKeysId
        })
        .catch((err) => {
          this.$message.destroy()
          this.$message.error(err)
        })
    },
    clickNextLevel(item) {
      //下级按钮
      this.breadcrumbText = item.name
      var param = {
        kind:this.tabValue,
        userId:item.userId,
        uname:item.uname
      }
      selectUser(param)
        .then((res) => {
          if(this.tabValue == 'u'){
            var data = res.data.data1
          } else {
            var data = res.data.data2
          }
          this.tabelData  = data
          data.forEach((item) => {
              item.type = this.chooseType
              this.searchData.push(item)
          })
        })
        .catch((err) => {
          this.$message.destroy()
          this.$message.error(err)
        })
    },
    breadcrumbAllBtn() {
      //面包屑全部点击
      this.breadcrumbText = ''
      this.getAllSearchData()
    },
    onSelectChange(selectedRowKeys) {
      console.log(selectedRowKeys)
      this.selectedRowKeys = selectedRowKeys
      console.log(this.allUserData)
      const tempArr = this.allUserData.filter(
        (a) =>
          a.userId === selectedRowKeys || selectedRowKeys.includes(a.userId)
      )
      this.checkedArr = [...tempArr]
    },
    //快速查询
    quikSearch() {
      if (!this.keywords) {
        this.$message.destroy()
        this.$message.warning('请输入关键字')
        return false
      }
    },
    //对象列表选择
    checkEvent(e) {
      const tempArr = this.searchUser.filter(
        (a) => a.id === this.checkedUser || this.checkedUser.includes(a.id)
      )
      this.checkedArr = [...tempArr]
      if (!this.single) {
        this.indeterminate =
          !!this.checkedUser.length &&
          this.checkedUser.length < this.searchUser.length
        this.checkAll = this.checkedUser.length === this.searchUser.length
      }
    },
    //删除已选对象
    tagClose(id) {
      console.log(id)
      const index = this.checkedArr.findIndex(
        (item) => item === id || item.userId === id
      )
      // if (index > -1) {
      //   this.checkedArr.splice(index, 1)
      //   if (this.single) {
      //     this.checkedUser.splice(index, 1)
      //   } else {
      //     this.checkedUser = ''
      //   }
      // }
      if (index > -1) {
        this.checkedArr.splice(index, 1)
        if (!this.single) {
          this.selectedRowKeys.splice(index, 1)
        } else {
          this.selectedRowKeys = []
        }
      }
    },
    //确定
    handleOk() {
      //dingzhongming/104512/丁忠明,dingzhijie/104619/丁质洁
        this.myManager = []
        this.checkedArr.forEach((item) => {
          this.myManager.push(
            (this.chooseType + '/' + item.userId + '/' + item.uname)
          )
        })
      this.myVisible = false;
      console.log(this.searchData)
      this.$emit('selectFunc', this.checkedArr)
    },
    //清空
    reset() {
      this.checkedArr = []
      this.checkedUser = null
      this.selectedRowKeys = []
      //this.checkAll = this.indeterminate = false
    },
    //返回勾选的对象给父组件
    getData() {
      return this.checkedArr
    },
    searchChoose(item) {
      console.log('表单:', this.form)
      let data
      this.form = Object.assign(this.form, item)
      data = Object.assign(
        {
          type: 'mo',
          tabType: 'm',
          hideSelfId: '103677',
          delIds: '',
          isThisSession: true,
          strYear: '',
          query_strJG: '',
          strSId: '',
          showmobile: false,
          strDutyTag: this.strDutyTag.join('/')
        },
        this.form
      )
    },
  },
  computed: {},
  watch: {
  }
}
</script>

<style lang="less" scoped>
.choose-object {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .select-manager {
    width: calc(100% - 74px);
    margin-right: 10px;
  }
}

.footer-btns {
  width: 100%;
  height: 100%;
  text-align: center;
}

.quik-search {
  height: 46px;
  line-height: 32px;
  // padding-bottom: 10px;
  border-bottom: 1px solid #e8e8e8;
  margin-bottom: 10px;
  span {
    font-size: 16px;
    color: #333;
  }
  input {
    width: 200px;
    margin-right: 15px;
  }
  /deep/.ant-input {
    height: 34px;
    line-height: 34px;
    border-radius: 2px;
  }
}

.card-container {
  display: inline-block;
  background: #f5f5f5;
  border-radius: 4px;
  border: 1px solid #f5f5f5;
  width: 33%;
  // margin: 14px 0 0 0;
  overflow: hidden;
  box-shadow: 0 0 6px 0 #e2e2e2;
  /deep/.ant-tabs-card .ant-tabs-content {
    height: calc(100% - 40px);
    margin-top: -16px;
    overflow-y: auto;
  }
  /deep/.ant-tabs-card .ant-tabs-content .ant-tabs-tabpane {
    background: #fff;
    padding: 0;
  }
  /deep/.ant-tabs-card .ant-tabs-bar {
    border-color: #fff;
  }
  /deep/.ant-tabs-card .ant-tabs-bar .ant-tabs-nav-scroll {
    background-color: #f5f5f5;
  }
  /deep/.ant-tabs-card .ant-tabs-bar .ant-tabs-tab {
    border-color: transparent;
    background: transparent;
    border-radius: 0;
    padding: 0 15px;
  }
  /deep/.ant-tabs-card .ant-tabs-bar .ant-tabs-tab-active {
    border-color: #fff;
    background: #fff;
  }
}
.right-title {
  display: block;
  background-color: #f5f5f5;
  height: 40px;
  line-height: 40px;
  padding-left: 16px;
}
.right-choice {
  display: inline-block;
  width: 80%;
  border-radius: 4px;
  border: 1px solid #f5f5f5;
  margin: 14px 0 0 15px;
  overflow: hidden;
  box-shadow: 0 0 6px 0 #e2e2e2;
  margin-top: 0px;

  .data-type {
    height: 260px;
    overflow-y: auto;
  }

  .list-title {
    line-height: 40px;
    height: 40px;
    padding: 0 0 0 5px;
    margin: 0 15px;
    border-bottom: 1px solid #e8e8e8;

    .check-all {
      float: right;
    }
  }

  .check-list {
    height: 310px;
    margin: 12px 15px 0 5px;
    overflow-y: auto;

    .ant-radio-wrapper {
      margin: 0 0 10px 10px;
    }

    .ant-checkbox-wrapper {
      margin: 0 0 10px 10px;
    }
  }

  .area-split {
    display: block;
    margin: 0 15px;
    height: 1px;
    background-color: #f5f5f5;
    box-shadow: 0 0 1px 0 #e2e2e2;
  }

  .checked-tags {
    height: 70px;
    margin: 12px 15px 12px 5px;
    overflow-y: auto;
    .ant-tag {
      margin: 0 0 10px 10px;
      height: 25px;
      line-height: 25px;

      .anticon-close {
        font-size: 14px;
        color: #1890ff;

        &:hover {
          color: #1890ff;
        }
      }
    }
  }
}

.ant-select + .ant-select,
.ant-select + .ant-input {
  margin-left: 6px;
}
.container {
  .flex-space-between();
  width: 100%;
}
.card-container {
  width: 43%;
  height: 460px;
  border-radius: 4px;
  border: 1px solid #f5f5f5;
  overflow: hidden;
  box-shadow: 0 0 6px 0 #e2e2e2;
  background-color: #fff;
  > div {
    height: 100%;
    overflow-x: auto;
  }
}
.right-title-box {
  .flex-space-between();
  width: 100%;
}
// 折叠面板样式重置
.card-container {
  .header-content {
    position: relative;
    .menu_head_select_ico {
      color: rgb(223, 223, 223);
      font-size: 12px;
      margin-right: 10px;
    }
  }
  /deep/.ant-collapse-content {
    border: none;
  }
  /deep/ .ant-collapse > .ant-collapse-item {
    border: none;
  }
  /deep/.ant-collapse {
    background-color: #fff;
    border: none;
  }
  .next-level {
    color: #1890ff;
    cursor: pointer;
  }
  .select-item {
    padding-left: 25px;
  }
}
.secondary-li {
  display: block;
  height: 38px;
  line-height: 38px;
}
.secondary-li:hover {
  background: #f8f8f8;
}
.breadcrumb {
  display: flex;
  align-items: center;
  padding-right: 16px;
  i {
    font-size: 12px;
    margin: 0 5px;
  }
  .all-btn {
    color: #1890ff;
    cursor: pointer;
  }
}
/deep/ .ant-checkbox-group {
  display: block;
}
/deep/ .ant-collapse-content > .ant-collapse-content-box {
  padding: 0 16px;
}
</style>